package com.daykw.ip.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.pager.Pager;

import com.daykw.ip.model.TArticleInfo;
import com.daykw.ip.model.TArticleTask;
import com.daykw.ip.model.TFixArticle;
import com.daykw.ip.util.Const;
import com.daykw.ip.util.MongoDBUtil;
import com.daykw.ip.util.SpringContextHolder;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;

public class FixMogoDBTask {
	private static Logger logger = Logger.getLogger(FixMogoDBTask.class);

	public void doStart() {

		try {
			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			MongoCollection<org.bson.Document> coll = MongoDBUtil.instance.getCollection(Const.MDB_DB, "article");
			
			 MongoCursor<Document> list = coll.find(Filters.eq("uptime",1)).iterator();
			 while (list.hasNext()) {
					Document _doc = list.next();
					String aid = _doc.getString("aid");
					TFixArticle fix = new TFixArticle();
					fix.setAid(aid);
					xhsDao.fastInsert(fix);
			 }
			 
		} catch (Exception e) {
			logger.error("", e);
		}

	}//
	
	
	
	
	public void doFixArticle() {
		try {

			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			MongoCollection<org.bson.Document> coll = MongoDBUtil.instance.getCollection(Const.MDB_DB, "article");
			SimpleDateFormat fpdate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
			Record fix = xhsDao.fetch("t_fix_page", Cnd.where("type", "=", "article"));
			String lastid = fix.getString("lastid");
			int size = fix.getInt("page_size");
			int page = fix.getInt("page");
			while (lastid != null) {
				MongoCursor<Document> list = MongoDBUtil.instance.findByPage3(coll, lastid, size);
				if (list == null || !list.hasNext()) {
					lastid = null;
					logger.info("全部修复完毕");
					break;
				}
				
				while (list.hasNext()) {
					Document _doc = list.next();
					ObjectId _id = _doc.getObjectId("_id");
					String time = null;
					String ptime = null;
					Object t = _doc.get("time");
					String aid = _doc.getString("aid");
					Integer post_time = _doc.getInteger("post_time");
					if(t!=null) {
						if (t instanceof Integer) {
							Integer tt = (Integer) t;
							Long tttt = (long) tt;
							Date ttt = new Date(tttt * 1000);
							time = fpdate.format(ttt);
						} else if (t instanceof String) {
							time = (String) t;
						}else {
							ArrayList<String>	times = (ArrayList<String>) t;
							time = times.get(0);
						}
						
						if(post_time!=null) {
							Long pt = (long) post_time;
							Date ptt = new Date(pt * 1000);
							ptime = fpdate.format(ptt);
						}else {
							Record r = xhsDao.fetch("t_article_info", Cnd.where("article_id", "=", aid));
							if(r!=null) {
								Date pdate = (Date) r.get("pub_date");
								ptime = fpdate.format(pdate);
							}else {
								logger.info("mysql中沒有對應的aid:"+aid);
								continue;
								
							}
							
						}
						
						
						if (!time.equals(ptime)) {
							logger.info("aid:"+aid+",time不对,time:"+time+",post_time:"+ptime);
							org.bson.Document newdoc = new org.bson.Document();
							newdoc.put("time", ptime);
							newdoc.put("uptime", 1);
							coll.updateOne(Filters.eq("aid", aid), new org.bson.Document("$set", newdoc));
						}
						
					}
					
					
					
					lastid = _id.toString();
				}
				page++;
				xhsDao.update("t_fix_page", Chain.make("lastid", lastid).add("page", page), Cnd.where("id", "=", 1));
				logger.info("完成修复mogodb第:" + page + "页");
				
				
			}

		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void doFixComment() {
		try {

			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			MongoCollection<org.bson.Document> coll = MongoDBUtil.instance.getCollection(Const.MDB_DB, "comment");
			SimpleDateFormat fpdate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
			int count = 0;
			for (int i = 230; i <= 627; i++) {
				Pager pager = xhsDao.createPager(i, 1000);
				List<Record> relist = xhsDao.query("t_comment_info", Cnd.where("create_date", ">=", 2018062000), pager);
			
				for (Record re : relist) {
					String comment_id = re.getString("comment_id");
					Document doc = MongoDBUtil.instance.findByOne(coll, "id", comment_id);
					Date pdate = (Date) re.get("pub_date");
					String pub_date = fpdate.format(pdate);
					String aid = re.getString("article_id");
					if (doc != null) {
						String time = null;
						Object t = doc.get("time");
						if (t instanceof Integer) {
							Integer tt = (Integer) t;
							Long tttt = (long) tt;

							Date ttt = new Date(tttt * 1000);
							time = fpdate.format(ttt);
						} else if (t instanceof String) {
							time = (String) t;
						}else {
							ArrayList<String>	times = (ArrayList<String>) t;
							time = times.get(0);
						}

						if (!time.equals(pub_date)) {
							Date new_pub_date = fpdate.parse(time);
							Integer new_pdate = Integer.parseInt(date.format(new_pub_date));
							xhsDao.update("t_comment_info",
									Chain.make("pub_date", new_pub_date).add("pdate", new_pdate),
									Cnd.where("comment_id", "=", comment_id));
							org.bson.Document newdoc = new org.bson.Document();
							newdoc.put("pdate", new_pdate);
							coll.updateOne(Filters.eq("id", comment_id), new org.bson.Document("$set", newdoc));
							logger.info("完成一条需要修复的第:" + count + "条,共：" + relist.size() + ",第" + i + "页");
						} else {
							logger.info("不需要修复:" + count + "条,共：" + relist.size() + ",第" + i + "页");
						}
					} else {
						xhsDao.clear("t_comment_info", Cnd.where("comment_id", "=", comment_id));
						xhsDao.update("t_article_task", Chain.make("comment_status", 0), Cnd.where("aid", "=", aid));
						logger.info("完成一条不需要修复的第:" + count + "条,共：" + relist.size() + ",第" + i + "页");
					}
					count++;
				}
			}

		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void doFixUserAtrticle() {
		try {
			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			List<Record> re = xhsDao.query("t_article_task", Cnd.where("status", "=", 9));
			int count = 0;
			int total = re.size();
			for (Record r : re) {
				String aid = r.getString("aid");
				Record u = xhsDao.fetch("t_fix_article", Cnd.where("aid", "=", aid));

				String auid = u.getString("author_id");

				xhsDao.update("t_article_task", Chain.make("user_id", auid), Cnd.where("aid", "=", aid));
				xhsDao.update("t_article_info", Chain.make("user_id", auid), Cnd.where("article_id", "=", aid));
				count++;

				System.out.println("###修复数量:" + count + ",总数:" + total);

			}

		} catch (Exception e) {

		}
	}

	public void doFixAtrticle() {
		try {

			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			MongoCollection<org.bson.Document> coll = MongoDBUtil.instance.getCollection(Const.MDB_DB, "article");
			SimpleDateFormat fpdate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
			Record re = xhsDao.fetch("t_fix_page", Cnd.where("type", "=", "article"));
			String lastid = re.getString("lastid");
			int pageSize = re.getInt("page_size");
		
			int page = re.getInt("page");

			while (lastid != null) {
				MongoCursor<Document> list = MongoDBUtil.instance.findByPage3(coll, lastid, pageSize);
				if (list == null || !list.hasNext()) {
					lastid = null;
					logger.info("全部修复完毕");
					break;
				}
				int count = 0;
				int fixcount = 0;

				// String pdate = null;

				while (list.hasNext()) {
					Document _doc = list.next();
					ObjectId _id = _doc.getObjectId("_id");
					String old_aid = _doc.getString("aid");
					String new_aid = null;
					Object content = _doc.get("content");
					Document author = (Document) _doc.get("author");
					if (content != null) {
						Document info = (Document) content;
						new_aid = info.getString("id");
					} else {
						Document info = (Document) _doc.get("noteInfo");
						new_aid = info.getString("id");
					}
					if (count % 1000 == 0) {
						System.out.println("count:" + count);
					}

					String user_id = author.getString("id");
					// 如果相等
					if (old_aid.equals(new_aid)) {
						lastid = _id.toString();
						count++;
						continue;
					} else {
						// 如果不相等
						logger.info("#########发现一个待修复的记录:" + old_aid + ",修复总数:" + fixcount + "#############");
						Document doc = MongoDBUtil.instance.findByOne(coll, "aid", new_aid);
						if (doc != null) {
							MongoDBUtil.instance.deleteById(coll, _id.toString());
							TArticleInfo a = xhsDao.fetch(TArticleInfo.class, Cnd.where("article_id", "=", new_aid));
							if (a == null) {
								MongoDBUtil.instance.deleteById(coll, doc.getObjectId("_id").toString());
								xhsDao.update(TArticleTask.class, Chain.make("status", 9),
										Cnd.where("aid", "=", old_aid));
							}
						} else {

							TArticleInfo a = xhsDao.fetch(TArticleInfo.class, Cnd.where("article_id", "=", new_aid));

							if (a == null) {
								xhsDao.clear(TArticleInfo.class, Cnd.where("article_id", "=", old_aid));
								MongoDBUtil.instance.deleteById(coll, _id.toString());
								xhsDao.update(TArticleTask.class, Chain.make("status", 9),
										Cnd.where("aid", "=", old_aid));
							} else {
								org.bson.Document newdoc = new org.bson.Document();
								newdoc.put("aid", new_aid);
								newdoc.put("user_id", user_id);
								newdoc.put("fix", 1);
								coll.updateOne(Filters.eq("aid", old_aid), new org.bson.Document("$set", newdoc));
								xhsDao.clear(TArticleInfo.class, Cnd.where("article_id", "=", old_aid));
								xhsDao.update(TArticleTask.class, Chain.make("status", 9),
										Cnd.where("aid", "=", old_aid));
							}

						}
						count++;
						fixcount++;
					}

					lastid = _id.toString();
				}
				page++;
				xhsDao.update("t_update_aid", Chain.make("aid", lastid).add("page", page), Cnd.where("id", "=", 1));
				logger.info("完成修复mogodb第:" + page + "页");

			}

		

		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void doFixUser() {
		try {

			NutDao xhsDao = SpringContextHolder.getBean("xhsDao");
			MongoCollection<org.bson.Document> coll = MongoDBUtil.instance.getCollection(Const.MDB_DB, "article");
			Record re = xhsDao.fetch("t_fix_page", Cnd.where("id", "=", 1));
			int pageSize = re.getInt("page_size");
			String lastid = re.getString("lastid");
			int page = re.getInt("page");

			while (lastid != null) {
				MongoCursor<Document> list = MongoDBUtil.instance.findByPage3(coll, lastid, pageSize);
				if (list == null || !list.hasNext()) {
					lastid = null;
					logger.info("全部修复完毕");
					break;
				}
				int count = 0;
				int fixcount = 0;

				while (list.hasNext()) {
					Document _doc = list.next();
					ObjectId _id = _doc.getObjectId("_id");

					String aid = null;
					Object content = _doc.get("content");
					String user_id = (String) _doc.get("user_id");
					Document author = (Document) _doc.get("author");
					if (content != null) {
						Document info = (Document) content;
						aid = info.getString("id");

					} else {
						Document info = (Document) _doc.get("noteInfo");
						aid = info.getString("id");

					}
					if (count % 1000 == 0) {
						logger.info("#######总数count:" + count + ",修复总数:" + fixcount);
					}
					String author_id = null;
					if (author == null) {
						author_id = (String) _doc.get("userId");
						if (StringUtils.isEmpty(author_id)) {
							xhsDao.update(TArticleTask.class, Chain.make("status", 8), Cnd.where("aid", "=", aid));
							continue;
						}

					} else {
						author_id = author.getString("id");
					}

					if (StringUtils.isNotEmpty(user_id) && StringUtils.isNotEmpty(author_id)) {
						// 如果不相等
						if (!user_id.equals(author_id)) {
							try {
								xhsDao.update(TArticleTask.class, Chain.make("status", 9), Cnd.where("aid", "=", aid));

								TFixArticle fix = new TFixArticle();
								fix.setAid(aid);
								fix.setUser_id(user_id);
								fix.setStatus(0);
								fix.setAuthor_id(author_id);

								xhsDao.fastInsert(fix);

								MongoDBUtil.instance.deleteById(coll, _id.toString());
								// logger.info("#########发现一个待修复的记录,修复成功:" + aid
								// + ",修复总数:" + fixcount + "#############");
								fixcount++;
							} catch (Exception e) {
								xhsDao.update(TArticleTask.class, Chain.make("status", 10), Cnd.where("aid", "=", aid));
								// logger.info("#########发现一个待修复的记录,修复失败:" + aid
								// + ",修复总数:" + fixcount + "#############");
							}

						}

					}
					count++;
					lastid = _id.toString();
				}
				page++;
				xhsDao.update("t_fix_page", Chain.make("lastid", lastid).add("page", page), Cnd.where("id", "=", 1));
				logger.info("完成修复mogodb第:" + page + "页");

			}

		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
